// 仪表盘功能
document.addEventListener('DOMContentLoaded', function() {
    // 检查用户是否已登录
    if (!window.authManager || !window.authManager.checkAuth()) {
        window.location.href = 'login.html';
        return;
    }
    
    // 初始化仪表盘
    initDashboard();
});

// 初始化仪表盘
function initDashboard() {
    const user = window.authManager.currentUser;
    
    // 显示用户信息
    document.getElementById('userName').textContent = user.username;
    
    // 初始化行为分析器
    window.behaviorAnalyzer = new BehaviorAnalyzer(user.id);
    
    // 分析行为并更新UI
    const behaviorData = window.behaviorAnalyzer.analyzeTransactions();
    updateDashboard(behaviorData);
    
    // 设置事件监听器
    setupDashboardEvents();
}

// 更新仪表盘显示
function updateDashboard(behaviorData) {
    // 更新偏差雷达图
    updateBiasRadar(behaviorData.biases);
    
    // 更新行为标签
    updateBehaviorTags(behaviorData.tags);
    
    // 更新洞察建议
    updateInsights(behaviorData.insights);
    
    // 更新交易历史
    updateTransactionHistory();
}

// 更新偏差雷达图
function updateBiasRadar(biases) {
    // 使用Chart.js绘制雷达图
    const ctx = document.getElementById('biasRadar').getContext('2d');
    
    if (window.biasChart) {
        window.biasChart.destroy();
    }
    
    window.biasChart = new Chart(ctx, {
        type: 'radar',
        data: {
            labels: ['过度自信', '损失厌恶', '处置效应', '确认偏误', '羊群效应'],
            datasets: [{
                label: '行为偏差程度',
                data: [
                    biases.overconfidence,
                    biases.lossAversion,
                    biases.dispositionEffect,
                    biases.confirmationBias,
                    biases.herdBehavior
                ],
                backgroundColor: 'rgba(54, 162, 235, 0.2)',
                borderColor: 'rgba(54, 162, 235, 1)',
                pointBackgroundColor: 'rgba(54, 162, 235, 1)',
                pointBorderColor: '#fff',
                pointHoverBackgroundColor: '#fff',
                pointHoverBorderColor: 'rgba(54, 162, 235, 1)'
            }]
        },
        options: {
            scales: {
                r: {
                    angleLines: {
                        display: true
                    },
                    suggestedMin: 0,
                    suggestedMax: 100
                }
            }
        }
    });
}

// 更新行为标签
function updateBehaviorTags(tags) {
    const tagsContainer = document.getElementById('behaviorTags');
    tagsContainer.innerHTML = '';
    
    if (tags.length === 0) {
        tagsContainer.innerHTML = '<div class="no-tags">未检测到明显的行为偏差</div>';
        return;
    }
    
    tags.forEach(tag => {
        const tagElement = document.createElement('div');
        tagElement.className = `behavior-tag ${tag.type}`;
        tagElement.innerHTML = `
            <h4>${tag.name}</h4>
            <p>${tag.description}</p>
        `;
        tagsContainer.appendChild(tagElement);
    });
}

// 更新洞察建议
function updateInsights(insights) {
    const insightsContainer = document.getElementById('insights');
    insightsContainer.innerHTML = '';
    
    insights.forEach(insight => {
        const insightElement = document.createElement('div');
        insightElement.className = `insight ${insight.type}`;
        insightElement.innerHTML = `
            <h4>${insight.title}</h4>
            <p>${insight.content}</p>
            <div class="suggestion">建议: ${insight.suggestion}</div>
        `;
        insightsContainer.appendChild(insightElement);
    });
}

// 更新交易历史
function updateTransactionHistory() {
    const transactions = window.behaviorAnalyzer.transactions;
    const historyContainer = document.getElementById('transactionHistory');
    historyContainer.innerHTML = '';
    
    if (transactions.length === 0) {
        historyContainer.innerHTML = '<div class="no-transactions">暂无交易记录</div>';
        return;
    }
    
    // 显示最近10笔交易
    const recentTransactions = transactions
        .sort((a, b) => new Date(b.transactionDate) - new Date(a.transactionDate))
        .slice(0, 10);
    
    recentTransactions.forEach(transaction => {
        const transactionElement = document.createElement('div');
        transactionElement.className = 'transaction-item';
        
        const profitClass = transaction.profit >= 0 ? 'profit' : 'loss';
        const profitText = transaction.profit >= 0 ? 
            `+${transaction.profit.toFixed(2)}` : 
            `${transaction.profit.toFixed(2)}`;
        
        transactionElement.innerHTML = `
            <div class="transaction-main">
                <span class="asset">${transaction.assetCode}</span>
                <span class="type">${transaction.type === 'buy' ? '买入' : '卖出'}</span>
                <span class="amount">${transaction.quantity}股 @ ¥${transaction.price.toFixed(2)}</span>
                <span class="profit ${profitClass}">${profitText}</span>
            </div>
            <div class="transaction-date">${formatDate(transaction.transactionDate)}</div>
        `;
        
        historyContainer.appendChild(transactionElement);
    });
}

// 设置仪表盘事件
function setupDashboardEvents() {
    // 模拟交易按钮
    const simulateBtn = document.getElementById('simulateTrade');
    if (simulateBtn) {
        simulateBtn.addEventListener('click', function() {
            // 打开模拟交易面板
            openSimulationPanel();
        });
    }
    
    // 生成报告按钮
    const reportBtn = document.getElementById('generateReport');
    if (reportBtn) {
        reportBtn.addEventListener('click', function() {
            generateBehaviorReport();
        });
    }
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
}

// 打开模拟交易面板
function openSimulationPanel() {
    // 实现模拟交易功能
    alert('模拟交易功能开发中...');
}

// 生成行为报告
function generateBehaviorReport() {
    // 实现PDF报告生成功能
    alert('行为报告生成功能开发中...');
}